<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Amitav Roy
 * Date: 1/27/13
 * Time: 11:05 AM
 * To change this template use File | Settings | File Templates.
 */
class Alias_model extends CI_Model {
  protected $table = 'url_alias';

  // loading the constructor
  public function __construct() {
    parent::__construct();
  }

  // public function to get the alias
  public function get_alias($id, $type = 'node', $vid = null) {
    return $this->fetch_alias($id, $type);
  }

  public function get_system_url($alias) {
    return $this->fetch_system_url($alias);
  }

  // function to query the alias table
  protected function fetch_alias($id, $type) {
    if ($type == 'node') {
      $source = 'node/' . $id;
    }
    elseif ($type == 'term') {
      $source = 'taxonomy/term/' . $id;
    }
    else {
      $source = 'user/' . $id;
    }

    $this->db->select('alias');
    $this->db->where('source', $source);
    $query = $this->db->get($this->table);
    $result = $query->result_array();


    return $result[0]['alias'];
  }

  // find the system url from alias
  protected function fetch_system_url($alias) {
    $this->db->select('source');
    $this->db->where('alias', $alias);
    $query = $this->db->get($this->table);
    $result = $query->result_array();

    if ($result)
      return $result[0]['source'];
  }
}
